import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-05-05
 * Time: 8:42
 */
public class Solution {

    /**
     *  字符串反转
     * @param str
     * @return
     */
    public String reverse(String str) {
        char[] arr = str.toCharArray();
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            char temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
        return String.valueOf(arr);
    }

    public String ReverseSentence(String str) {
        if(str == null || str.length() == 0){
            return str;
        }
        List<String> list = new ArrayList<>();
        int i = 0;
        int begin = 0;
        // 将每个单词分离出来
        while (i < str.length()) {
            // 找到一个单词的首字母
            while (i < str.length() && str.charAt(i) == ' ') {
                i++;
            }
            begin = i;
            // 找到一个单词后面的第一个空格
            while (i < str.length() && str.charAt(i) != ' ') {
                i++;
            }
            // 将单词分离出来
            list.add(str.substring(begin, i));
            i++;
        }
        // 将所有的单词进行反转
        List<String> rev = new ArrayList<>();
        for (String s : list) {
            rev.add(reverse(s));
        }
        // 对反转结果进行拼接
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : rev) {
            stringBuilder.append(s).append(" ");
        }
        // 删除最后多余的空格
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        // 再将整体反转
        return reverse(stringBuilder.toString());
    }
}
